package com.yyh.synctool.client.controller;

import com.yyh.result.JsonResult;
import com.yyh.synctool.client.job.TaskInfo;
import com.yyh.synctool.client.component.TaskManagement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

/**
 * 控制器，用于管理任务
 * @author xuan
 * @date 2021/12/6
 */
@RestController
@RequestMapping("/task")
public class ManagementController
{
    private TaskManagement taskManagement;

    @Autowired
    public ManagementController(TaskManagement taskManagement) {
        this.taskManagement = taskManagement;
    }

    /** 任务展示 */
    @GetMapping("/show-tasks")
    public JsonResult showTasks() {
        Collection<TaskInfo> taskInfos = taskManagement.showTasks();
        return JsonResult.getSuccess(taskInfos);
    }

    /** 手动执行一次任务 */
    @GetMapping("/exec")
    public JsonResult exec(@RequestParam("taskId") String taskId) {
        boolean result = taskManagement.execute(taskId);
        if (result) {
            return JsonResult.getSuccess(taskId);
        } else {
            return JsonResult.getFailure("执行任务[" + taskId + "]失败");
        }
    }

    /** 开启/关闭定时任务 */
    @GetMapping("/switch-task")
    public JsonResult switchTask(@RequestParam("taskId") String taskId) {
        taskManagement.switchTask(taskId);
        return JsonResult.getSuccess("操作成功");
    }

    /** 开启调度器 */
    @GetMapping("/start")
    public String start() {
        taskManagement.start();
        return "开启定时任务";
    }

    /** 停止调度器 */
    @GetMapping("/stop")
    public String stop() {
        taskManagement.stop();
        return "关闭定时任务";
    }
}
